<?php

namespace app\middleware;

use app\ErrorCode;
use app\exception\ApiException;
use app\model\Auth;
use app\model\Menu;
use app\model\Role;
use app\model\AdminRole;
use app\service\JwtService;
use think\Response;
use app\Request;

class AuthMiddleware
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $routePath = $request->pathinfo();
        // 白名单路由跳过验证
        $publicRoutes = config("custom.no_login_action");
        if (in_array($routePath, $publicRoutes)) {
            return $next($request);
        }

        $token = $request->header('Authorization');
        if (!$token) {
            throw new ApiException('请先登录', ErrorCode::UNAUTHORIZED);
        }

        $res = JwtService::getInstance()->decode($token);
        $userInfo = $this->getUserMenus($res);
        $request->setUserInfo($userInfo);
        return $next($request);
    }

    /**
     * 获取用户菜单信息
     *
     * @param mixed $user
     * @return array
     */
    protected function getUserMenus($user)
    {
        $userId = $user->id;
        if ($user->type === 'supplier_admin') {
            return [
                "id" => $userId,
                "username" => $user->username,
                "role_id" => Role::where("name", $user->type)->value("id"),
                "menu_ids" => Menu::where("status", "=", 1)->column("id"),
            ];
        }
        $roleId = AdminRole::where("admin_id", $userId)->value("role_id");
        $menuIds = $roleId ? Auth::where("role_id", $roleId)->column("menu_id") : [];

        // 将菜单信息合并到用户信息中
        return [
            "id" => $userId,
            "username" => $user->username,
            "role_id" => $roleId,
            "menu_ids" => $menuIds
        ];
    }
}